package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.PreLookHouseBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.TimeBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.EventBusEvent;
import com.weixin.paleituo.help.TextWatcherImp;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.DateTools;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.SelectTimePopuWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 预约看房
 */
public class AppointmentsLookHouseActivity extends BasePersonActivity {

    @BindView(R.id.tv_concat_title_activity_appointments_look_house)
    TextView mTvConcatTitleActivityAppointmentsLookHouse;
    @BindView(R.id.et_activity_appointments_look_house)
    EditText mEtActivityAppointmentsLookHouse;
    @BindView(R.id.iv_del_activity_appointments_look_house)
    ImageView mIvDelActivityAppointmentsLookHouse;
    @BindView(R.id.tv_time_title_activity_appointments_look_house)
    TextView mTvTimeTitleActivityAppointmentsLookHouse;
    @BindView(R.id.et_timecontent_activity_appointments_look_house)
    EditText mEtTimecontentActivityAppointmentsLookHouse;
    @BindView(R.id.iv_timemore_activity_appointments_look_house)
    ImageView mIvTimemoreActivityAppointmentsLookHouse;
    @BindView(R.id.rl_timeroot_activity_appointments_look_house)
    RelativeLayout mRlTimerootActivityAppointmentsLookHouse;
    @BindView(R.id.tv_sure_activity_appointments_look_house)
    TextView mTvSureActivityAppointmentsLookHouse;
    Dialog mLoadingDialog;

    List<String> dateStrList=new ArrayList<>();
    List<String> timeStrList=new ArrayList<>();
    private SelectTimePopuWindow mSelectTimePopuWindow;
    private long mPrototypeRoomId;
    private int mHouseId;
    private LoadingPagerHead mLoadingPagerHead;
    private int mSign;
    private String mFullname;
    private String mHousename;

    @Override
    protected View getContentView(Context context) {
        mLoadingPagerHead = new LoadingPagerHead(this,0,Contans.SHARHOUSE_SOLDOUT_TYPE) {
            @Override
            protected void close() {


            }
            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(AppointmentsLookHouseActivity.this, R.layout.activity_appointments_look_house);
            }

            @Override
            protected void reLoading() {
                retry();
            }
        };

        return mLoadingPagerHead;
    }

    /**
     * 重试
     */
    private void retry() {

        Observable<StatusCode<PreLookHouseBean>> preLookHouseTime = ApiUtils.getApi().isPreLookHouseTime(BaseApplication.sUserInfoBean.getToken(), BaseApplication.getUserId(), mPrototypeRoomId);

        HttpUtil.getInstance().toSubscribe(preLookHouseTime, new ProgressSubscriber<PreLookHouseBean>(this) {
            @Override
            protected void _onNext(StatusCode<PreLookHouseBean> preLookHouseBeanStatusCode) {

                mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                PreLookHouseBean data = preLookHouseBeanStatusCode.getData();
                mSign = data.getSign();

                if (mSign ==1){
                    //不能添加
                    String appointmentTime = data.getAppointmentTime();
                    String linkman = data.getLinkman();

                    mEtTimecontentActivityAppointmentsLookHouse.setText(appointmentTime);
                    mEtActivityAppointmentsLookHouse.setText(linkman);
                    mEtActivityAppointmentsLookHouse.setFocusable(false);
                    mEtTimecontentActivityAppointmentsLookHouse.setFocusable(false);


                    mTvSureActivityAppointmentsLookHouse.setVisibility(View.INVISIBLE);
                    mIvDelActivityAppointmentsLookHouse.setVisibility(View.INVISIBLE);
                    mIvTimemoreActivityAppointmentsLookHouse.setVisibility(View.INVISIBLE);
                }

            }

            @Override
            protected void _onError(String message) {


                if (Contans.SHARE_HOUSE_SOLD_OUT.equalsIgnoreCase(message)){

                    mLoadingPagerHead.showPagerView(Contans.STATE_SOLDOUT);

                }else {
                mLoadingPagerHead.showPagerView(Contans.STATE_ERROR);

                }

            }
        },"",lifecycleSubject,false,true);


    }

    @Override

    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);
        mPrototypeRoomId = getIntent().getLongExtra(Contans.INTENT_EXTRA, 0);
        mHouseId = getIntent().getIntExtra(Contans.INTENT_DATA,0);
        mFullname = getIntent().getStringExtra("fullname");
        mHousename = getIntent().getStringExtra("housename");


        mTvTitle.setVisibility(View.VISIBLE);
        mTvTitle.setText("预约看房");
        mViewline.setVisibility(View.VISIBLE);
        mIvDelActivityAppointmentsLookHouse.setVisibility(View.INVISIBLE);
        retry();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mEtActivityAppointmentsLookHouse.addTextChangedListener(new TextWatcherImp() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                super.beforeTextChanged(s, start, count, after);
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String editable = mEtActivityAppointmentsLookHouse.getText().toString();
                String regEx = "[^\\u4E00-\\u9FA5]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(editable);
                String str = m.replaceAll("").trim();
                if (!editable.equals(str)) {
                    mEtActivityAppointmentsLookHouse.setText(str);
                    mEtActivityAppointmentsLookHouse.setSelection(str.length());
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                String s1 = mEtActivityAppointmentsLookHouse.getText().toString();
                if (StringUtils.isEmpty(s1)){
                    mIvDelActivityAppointmentsLookHouse.setVisibility(View.INVISIBLE);

                }else {
                    mIvDelActivityAppointmentsLookHouse.setVisibility(View.VISIBLE);

                }

            }
        });

    }
/*fullname	是	String	房源名
housename	是	String	楼盘名
*/
    public static void startActivity(Context context,Long prototypeRoomId,int houseId,String fullname,String housename) {
        Intent intent = new Intent(context, AppointmentsLookHouseActivity.class);

        intent.putExtra(Contans.INTENT_EXTRA,prototypeRoomId);
        intent.putExtra(Contans.INTENT_DATA,houseId);
        intent.putExtra("fullname",fullname);
        intent.putExtra("housename",housename);
        context.startActivity(intent);


    }


    @OnClick(R.id.iv_del_activity_appointments_look_house)
    public void onMIvDelActivityAppointmentsLookHouseClicked() {

        mEtActivityAppointmentsLookHouse.setText("");

    }

    @OnClick(R.id.rl_timeroot_activity_appointments_look_house)
    public void onMRlTimerootActivityAppointmentsLookHouseClicked() {

        if (mSign==1){
            return;
        }



   final      View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);

        if (dateStrList.size()>0 && timeStrList.size()>0){

            if (mSelectTimePopuWindow==null){

            mSelectTimePopuWindow = new SelectTimePopuWindow(this,dateStrList,timeStrList);
            mSelectTimePopuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mIvTimemoreActivityAppointmentsLookHouse.setImageResource(R.mipmap.lookhouse_down);
                }
            });

            }
            mIvTimemoreActivityAppointmentsLookHouse.setImageResource(R.mipmap.lookhouse_up);
            mSelectTimePopuWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);



        }else {


            Observable observable = ApiUtils.getApi().getTime(Contans.defaultToken).compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
                @Override
                public void accept(Disposable disposable) throws Exception {
                    if (mLoadingDialog == null) {
                        mLoadingDialog = LoadingDialogUtils.createLoadingDialog(AppointmentsLookHouseActivity.this, "");
                    }
                    LoadingDialogUtils.show(mLoadingDialog);
                }
            }).subscribeOn(AndroidSchedulers.mainThread());


            HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<TimeBean>(AppointmentsLookHouseActivity.this) {
                @Override
                protected void _onNext(StatusCode<TimeBean> timeBeanStatusCode) {

                    LoadingDialogUtils.closeDialog(mLoadingDialog);

                    TimeBean timeBean = timeBeanStatusCode.getData();
                    List<String> dateStr = timeBean.getDateStr();
                    List<String> timeStr = timeBean.getTimeStr();
                    if (dateStr!=null&&dateStr.size()>0&&timeBean!=null&&timeStr.size()>0){
                        dateStrList.clear();
                        timeStrList.clear();
                        dateStrList.addAll(dateStr);
                        timeStrList.addAll(timeStr);
                        if (mSelectTimePopuWindow==null){

                            mSelectTimePopuWindow = new SelectTimePopuWindow(AppointmentsLookHouseActivity.this,dateStrList,timeStrList);
                            mSelectTimePopuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                                @Override
                                public void onDismiss() {
                                    mIvTimemoreActivityAppointmentsLookHouse.setImageResource(R.mipmap.lookhouse_down);
                                }
                            });
                        }
                        mIvTimemoreActivityAppointmentsLookHouse.setImageResource(R.mipmap.lookhouse_down);
                        mSelectTimePopuWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

                    }


                }

                @Override
                protected void _onError(String message) {
                    LoadingDialogUtils.closeDialog(mLoadingDialog);




                }
            },"",lifecycleSubject,false,true);

        }








    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventBusEvent(EventBusEvent eventBusEvent){
        String time = eventBusEvent.getTime();
        if (!StringUtils.isEmpty(time)){
           String str =time .replaceAll("\\s*", "");

            mEtTimecontentActivityAppointmentsLookHouse.setText(str);


        }

    }




    @OnClick(R.id.tv_sure_activity_appointments_look_house)
    public void onSureOnclick(){
        String name = mEtActivityAppointmentsLookHouse.getText().toString();

        String time = mEtTimecontentActivityAppointmentsLookHouse.getText().toString();

        if (StringUtils.isEmpty(name)){

            ToastUtils.makeText("请输入联系人姓名");
            return;
        }

        if (StringUtils.isEmpty(time)){
            ToastUtils.makeText("请选择预约日期");
            return;
        }
        long gettime = DateTools.gettime(time);

        LogUtils.i(TAG,"选择择的时间撮"+gettime);
        long currentLong = DateTools.getcurrentTime();
        LogUtils.i(TAG,"当前的时间撮"+currentLong);

        if (gettime<currentLong){
            ToastUtils.makeText("选择时间不能小于当前时间");
            return ;
        }

        String format = DateTools.getFormat(gettime);

        //预约时间（yyyy-MM-dd HH）

        LogUtils.i(TAG,"传输入的时间格式"+format);

        Observable observable = ApiUtils.getApi().submintLookhouse(BaseApplication.sUserInfoBean.getToken(), BaseApplication.sUserInfoBean.getUserId(), mPrototypeRoomId, name, format,mHouseId,mFullname,mHousename)
                .compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mLoadingDialog == null) {
                            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(AppointmentsLookHouseActivity.this, "");
                        }
                        LoadingDialogUtils.show(mLoadingDialog);
                    }
                }).subscribeOn(AndroidSchedulers.mainThread());

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Object>(AppointmentsLookHouseActivity.this) {
            @Override
            protected void _onNext(StatusCode<Object> objectStatusCode) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                ToastUtils.makeText("预约成功");
                finish();
            }

            @Override
            protected void _onError(String message) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                ToastUtils.makeText("预约失败");

            }
        },"",lifecycleSubject,false,true);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
